//
//  SNSearchFriendVc.m
//  project
//
//  Created by 黄建华 on 2018/8/9.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "SNSearchFriendVc.h"
@interface SNSearchFriendVc ()<UITextFieldDelegate>

@property (nonatomic, strong) UITextField  *textfield;
@property (nonatomic, strong) SNShadowView *showUserView;
@property (nonatomic, strong) UIButton     *addFriendButton;
@property (nonatomic, assign) BOOL         isFriend;

@property (nonatomic, strong) SNEncourageButton           *button1;
@property (nonatomic, strong) SNEncourageButton           *button2;
@property (nonatomic, strong) UIImageView        *headImageV;
@property (nonatomic, strong) UILabel            *nickLabel;
@property (nonatomic, strong) UIView             *headView;
@property (nonatomic, strong) UILabel            *userIdLabel;
@property (nonatomic, strong) UIImageView        *gender;
@property (nonatomic, strong) FriednInviterModel *model;

@end

@implementation SNSearchFriendVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    CGFloat height = 0;
    if (KK_ShareData.ipx) {
        height = 20;
    }
    // Do any additional setup after loading the view.
    UIView *StateView = [[UIView alloc] init];
    StateView.frame           = CGRectMake(0, 0, kSCREEN_WIDTH, 20+height);
    StateView.backgroundColor = BBIGSTATECOLOR;
    [self.view addSubview:StateView];
    
    UIView *naView = [[UIView alloc] init];
    naView.frame           = CGRectMake(0, 20+FitSimpleIpx(0, 20), kSCREEN_WIDTH, 44);
    naView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:naView];
    
    _textfield                      = [[UITextField alloc] initWithFrame:CGRectMake(70, 20+FitSimpleIpx(0, 20), screenWidth -140, 44)];
    _textfield.textColor            = [UIColor blackColor];
    _textfield.placeholder          = SN_Text(@"用户ID/邮箱");
    _textfield.font                 = SNFONT(17);
    _textfield.textAlignment        = NSTextAlignmentCenter;
    _textfield.delegate             = self;
    _textfield.clearsOnBeginEditing = YES;
    [self.view addSubview:_textfield];
    
    UIButton *leftButton = [[UIButton alloc] init];
    leftButton.frame = CGRectMake(5, 20+FitSimpleIpx(0, 20), 44, 44);
    [leftButton setImageNormal:@"进入"];
    [leftButton addTarget:self action:@selector(backButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    
    UIImageView *shadowLine = [[UIImageView alloc] init];
    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44 -2, HHHWIDTH, 2);
    shadowLine.image = [UIImage image:@"lineImage"];
    [self.view addSubview:shadowLine];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *addFriendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addFriendButton.frame = CGRectMake(screenWidth - 44 -5, 33 + FitSimpleIpx(0, 20), 44, 44);
    [addFriendButton setImageNormal:@"F搜索"];
    addFriendButton.imageEdgeInsets = UIEdgeInsetsMake(2, 2, 4, 2);
    addFriendButton.center          = CGPointMake(screenWidth - 22 -10, leftButton.centerY);
    [self.view addSubview:addFriendButton];
    [addFriendButton addTarget:self action:@selector(addFriendButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self showUserViewUi];
}

- (void)showUserViewUi {
    _showUserView = [[SNShadowView alloc]initWithFrame:SNFRAME(20, 20+FitSimpleIpx(0, 20) + 44 +15, screenWidth -40, HHHHEIGHT *0.4 +20)];
    [self.view addSubview:_showUserView];
    _showUserView.layer.borderWidth = 0.5;
    _showUserView.layer.borderColor = SNCOLORGRAYLINE.CGColor;
    
    _headImageV                     = [[UIImageView alloc] init];
    _headImageV.frame               = SNFRAME(0, 0, 120, 120);
    _headImageV.layer.cornerRadius  = _headImageV.width/2.0;
    _headImageV.layer.masksToBounds = YES;
    _headImageV.image = [UIImage imageNamed:@"loginhead"];
    _headImageV.center              = CGPointMake(_showUserView.width/2, _showUserView.height *0.4);
    [_showUserView addSubview:_headImageV];
    
    _button1              = [[SNEncourageButton alloc] init];
    _button1.frame        = SNFRAME(0, 0, 50, 50);
    _button1.center       = CGPointMake(_headImageV.left - 50, _headImageV.centerY);
    _button1.tag          = 1;
    _button1.imageNormal  = @"点赞1";
    _button1.imageSelecte = @"点赞";
    [_button1 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_showUserView addSubview:_button1];
    
    UILabel *labale1 = [[UILabel alloc] init];
    labale1.textColor     = SNCOLORBLACK;
    labale1.font          = SNFONT(15.0);
    labale1.text          = SN_Text(@"点赞");
    labale1.frame         = SNFRAME(_button1.left -25, _button1.bottom + 7, 100, 20);
    labale1.textAlignment = NSTextAlignmentCenter;
    [_showUserView addSubview:labale1];
    
    _button2              = [[SNEncourageButton alloc] init];
    _button2.frame        = SNFRAME(0, 0, 50, 50);
    _button2.center       = CGPointMake(_headImageV.right +50, _headImageV.centerY);
    _button2.imageNormal  = @"鼓励1";
    _button2.imageSelecte = @"鼓励";
    _button2.tag          = 2;
    [_button2 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_showUserView addSubview:_button2];
    
    UILabel *labale2 = [[UILabel alloc] init];
    labale2.textColor     = SNCOLORBLACK;
    labale2.font          = SNFONT(15.0);
    labale2.text          = SN_Text(@"鼓励");
    labale2.textAlignment = NSTextAlignmentCenter;
    labale2.frame         = SNFRAME(_button2.left -25, _button2.bottom + 7, 100, 20);
    [_showUserView addSubview:labale2];
    
    _nickLabel               = [[UILabel alloc] init];
    _nickLabel.textColor     = SNCOLORBLACK;
    _nickLabel.font          = SNFONT(17.0);
    _nickLabel.frame         = SNFRAME(_headImageV.centerX - 80, _headImageV.bottom + 33, 160, 20);
    _nickLabel.textAlignment = NSTextAlignmentCenter;
    [_showUserView addSubview:_nickLabel];
    
    _gender = [[UIImageView alloc] init];
    [_showUserView addSubview:_gender];
    
    _userIdLabel               = [[UILabel alloc] init];
    _userIdLabel.textColor     = SNCOLORBLACK;
    _userIdLabel.font          = SNFONT(15.0);
    _userIdLabel.frame         = SNFRAME(_nickLabel.left, _nickLabel.bottom + 5, 160, 20);
    _userIdLabel.textAlignment = NSTextAlignmentCenter;
    [_showUserView addSubview:_userIdLabel];
    
    _addFriendButton                     = [[UIButton alloc] init];
    _addFriendButton.frame               = SNFRAME(20, _showUserView.bottom +66, screenWidth -40, 44);
    _addFriendButton.layer.cornerRadius  = 5.0;
    _addFriendButton.titleLabel.adjustsFontSizeToFitWidth = YES;
    _addFriendButton.titleLabel.minimumScaleFactor = 0.5;
    _addFriendButton.layer.masksToBounds = YES;
    _addFriendButton.backgroundColor     = SNCOLORBLACK;
    [_addFriendButton setTitle:SN_Text(@"添加为好友") forState:UIControlStateNormal];
    [_addFriendButton setTitle:SN_Text(@"添加为好友") forState:UIControlStateHighlighted];
    [_addFriendButton setTitleColor:SNCOLORWHITE forState:UIControlStateNormal];
    [_addFriendButton setTitleColor:SNCOLORGRAYLINE forState:UIControlStateHighlighted];
    [self.view addSubview:_addFriendButton];
    [_addFriendButton addTarget:self action:@selector(sureAddFriend) forControlEvents:UIControlEventTouchUpInside];
    _showUserView.hidden    = YES;
    _addFriendButton.hidden = YES;
}

- (CGFloat)getWidthWithText:(NSString *)text height:(CGFloat)height font:(CGFloat)font {
    CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                                     context:nil];
    
    return rect.size.width;
}

- (void)buttonClick:(UIButton *)sender {
    
    if (sender.tag == 1) {
        [_button1 EncourageButtonClickWithImageName:@"点赞"];
    }
    else
    {
        [_button2 EncourageButtonClickWithImageName:@"鼓励"];
    }
    
    [SN_Net friendClickWithType:sender.tag userid:StrByInt(_model.userId) Success:^(id object) {
        if (sender.tag == 1) {
            SHOWMBProgressHUD(SN_Text(@"点赞成功"), nil, nil, NO, 1.0);
            _button1.selected = YES;
        } else if (sender.tag == 2) {
            SHOWMBProgressHUD(SN_Text(@"鼓励成功"), nil, nil, NO, 1.0);
            _button2.selected = YES;
        }
    } fail:^(id object) {
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)sureAddFriend {
    if ([_addFriendButton.titleLabel.text isEqualToString:SN_Text(@"没有找到好友")]) {
        SHOWMBProgressHUD(SN_Text(@"没有找到好友"), nil, nil, NO, 2.0);
    }
    if ([_addFriendButton.titleLabel.text isEqualToString:SN_Text(@"已添加")]) {
        SHOWMBProgressHUD(SN_Text(@"已添加"), nil, nil, NO, 2.0);
    }
    if ([_addFriendButton.titleLabel.text isEqualToString:SN_Text(@"添加为好友")]) {
        [SN_Net friendWithInvitation:StrByInt(_model.userId) success:^(id object) {
            SHOWMBProgressHUD(SN_Text(@"已经发送好友请求"), nil, nil, NO, 2.0);
        } fail:^(id object) {
        }];
    }
}

- (void)updateInfoUi {
    _showUserView.hidden = NO;
    _nickLabel.text      = _model.showNickName;
    _userIdLabel.text    = [NSString stringWithFormat:@"ID:%d", _model.userId];
    [_headImageV sd_setImageWithURL:[NSURL URLWithString:_model.imagePathUrlString] placeholderImage:[UIImage imageNamed:@"loginhead"]];
    CGFloat width = [self getWidthWithText:_nickLabel.text height:20 font:17.0]+ 10;
    _nickLabel.frame = SNFRAME(_headImageV.centerX - width/2, _headImageV.bottom + 33, width, 20);
    _gender.frame    = SNFRAME(_nickLabel.right +5, _nickLabel.top - 7, 33, 33);
    if (_model.gender == 1) {
        _gender.image = [UIImage image:@"F男"];
    } else {
        _gender.image = [UIImage image:@"F女"];
    }
    
    [SN_Net friendWithSearchHomePage:StrByInt(_model.userId) success:^(id object) {
        NSDictionary *dic = object;
        NSDictionary *dicN = dic[@"data"];
        NSInteger is_encourage = [dicN[@"is_encourage"]integerValue];
        NSInteger is_thumb = [dicN[@"is_thumb"]integerValue];
        
        if (is_thumb == 1) {
            _button1.selected = YES;
        } else {
            _button1.selected = NO;
        }
        
        if (is_encourage == 1) {
            _button2.selected = YES;
        } else {
            _button2.selected = NO;
        }
    } fail:^(id object) {
    }];
}

- (void)addFriendButtonClick {
    if (_textfield.text.length == 0) {
        SHOWMBProgressHUD(SN_Text(@"请填写用户ID/邮箱"), nil, nil, NO, 2.0);
        return;
    }
    
    if ([self deptNumInputShouldNumber:_textfield.text] || [self isValidateEmail:_textfield.text]) {
        [_textfield resignFirstResponder];
        NSLog(@"[LOGINACCOUNT getObjectValue]>>>>>%@", [LOGINACCOUNT getObjectValue]);
        
        if (_textfield.text == SN_USER.user_id || [_textfield.text isEqualToString:[LOGINACCOUNT getObjectValue]]) {
            SHOWMBProgressHUD(SN_Text(@"不能添加自己"), nil, nil, NO, 2.0);
            
            return;
        }
        _model                  = [[FriednInviterModel alloc] init];
        _showUserView.hidden    = YES;
        _addFriendButton.hidden = NO;
        _button1.selected       = NO;
        _button2.selected       = NO;
        [SN_Net friendWithSearch:_textfield.text success:^(id object) {
            HIDDENMBProgressHUD;
            NSDictionary *dic = object;
            if (!dic) {
                //表示没有找到好友
                [_addFriendButton setTitle:SN_Text(@"没有找到好友") forState:UIControlStateNormal];
                [_addFriendButton setTitle:SN_Text(@"没有找到好友") forState:UIControlStateHighlighted];
                return;
            }
    
            _model.nickName = dic[@"nickname"];
            _model.gender = [dic[@"gender"]integerValue];
            _model.userId = [dic[@"user_id"]integerValue];
            _model.imagePathUrlString = dic[@"portrait"];
            
            if ([dic[@"is_friend"]integerValue] == 1) {
                _isFriend = YES;
                [_addFriendButton setTitle:SN_Text(@"已添加") forState:UIControlStateNormal];
                [_addFriendButton setTitle:SN_Text(@"已添加") forState:UIControlStateHighlighted];
            } else {
                _isFriend = NO;
                [_addFriendButton setTitle:SN_Text(@"添加为好友") forState:UIControlStateNormal];
                [_addFriendButton setTitle:SN_Text(@"添加为好友") forState:UIControlStateHighlighted];
            }
            [self updateInfoUi];
        } fail:^(id object) {
        }];
    } else {
        SHOWMBProgressHUD(SN_Text(@"用户ID/邮箱 格式不正确"), nil, nil, NO, 2.0);
        return;
    }
}

- (void)backButton {
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)isValidateEmail:(NSString *)email {
    NSString    *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest  = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:email];
}

- (BOOL)deptNumInputShouldNumber:(NSString *)str {
    if (str.length == 0) {
        return NO;
    }
    NSString    *regex = @"[0-9]*";
    NSPredicate *pred  = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
